#!/bin/sh

# Slackware build script for LibreOffice

# Copyright 2015-2020 Hunter Sezen California, USA
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

PRGNAM=libreoffice
VERSION=${VERSION:-7.0.2.2}
BUILD=${BUILD:-1}
TAG=${TAG:-_orb}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i586 ;;
    arm*) ARCH=arm ;;
       *) ARCH=$( uname -m ) ;;
  esac
fi

CWD=$(pwd)
TMP=${TMP:-/tmp/SBo}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

if [ "$ARCH" = "i586" ]; then
  SLKCFLAGS="-O2 -march=i586 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC"
  LIBDIRSUFFIX="64"
else
  SLKCFLAGS="-O2"
  LIBDIRSUFFIX=""
fi

set -eu

exists () {
  r=0; cwd="$(pwd)"
  while [ $# -gt 0 ]; do
    v=1; arg="$1"; shift
    case "$arg" in
      ''|*/ )
        :
      ;;
      /* )
        if [ -f "$arg" ] && [ -x "$arg" ]; then
          printf %s\\n "$arg"
          v=0
        fi
      ;;
      ./* )
        if [ -f "$arg" ] && [ -x "$arg" ]; then
          pre="$(cd -- "${arg%%/*}/" && pwd)"
          printf %s\\n "${pre%/}/$arg"
          v=0
        fi
      ;;
      */* )
        if [ -f "$arg" ] && [ -x "$arg" ]; then
          printf %s\\n "$(cd -- "${arg%%/*}/.." && pwd)/$arg"
          v=0
        fi
      ;;
      * )
        if [ -n "${PATH+x}" ]; then
          p=":${PATH:-$cwd}"
          while [ "$p" != "${p#*:}" ] && [ -n "${p#*:}" ]; do
            p="${p#*:}"; x="${p%%:*}"; z="${x:-$cwd}"; d="${z%/}/$arg"
            if [ -f "$d" ] && [ -x "$d" ]; then
              case "$d" in
                /* ) : ;;
                ./* ) pre="$(cd -- "${d%/*}/" && pwd)"; d="${pre%/}/$d" ;;
                * ) d="$(cd -- "${d%/*}/" && pwd)/$arg" ;;
              esac
              printf %s\\n "$d"
              v=0
              break
            fi
          done
        fi
      ;;
    esac
  [ $v = 0 ] || r=1
  done
  return $r
}

pkg () {
  case "$1" in
    -b )
      if exists "$2" >/dev/null 2>&1; then
        lib="${lib} $3"
      fi
    ;;
    -i )
      if [ -d "/usr/include/$2" ]; then
        lib="${lib} $3"
      fi
    ;;
    -l )
      if ldconfig -p | grep -q "$2"; then
        lib="${lib} $3"
      fi
    ;;
    -p )
      if pkg-config --exists "$2"; then
        lib="${lib} $3"
      fi
    ;;
    * )
      printf %s\\n "ERROR: option '$1' is unrecognized" >&2
      exit 1
    ;;
  esac
}

use () { case "$1" in "$2") : ;; *) lib="${lib} $3" ;; esac; }

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $PRGNAM-$VERSION
tar xvf $CWD/$PRGNAM-$VERSION.tar.xz
cd $PRGNAM-$VERSION
[ ! -f $CWD/$PRGNAM-src-$VERSION.tar.xz ] ||
  tar xvf $CWD/$PRGNAM-src-$VERSION.tar.xz
chown -R root:root .
find -L . -perm /111 -a \! -perm 755 -a -exec chmod 755 {} + \
  -o \! -perm /111 -a \! -perm 644 -a -exec chmod 644 {} +

lib=

case "${OPT:-0}" in
  0 ) LO_PREFIX='/usr' ;;
  * ) LO_PREFIX="/opt/$PRGNAM" ;;
esac

case "${HELP:-0}" in
  0 ) lib="${lib} --without-help" ;;
  html|online ) lib="${lib} --with-help=$HELP" ;;
  * ) lib="${lib} --with-help" ;;
esac

case "${LANGUAGES:=en-US}" in
  [aA][lL][lL] ) languages='ALL' ;;
  *[![:space:]]*|*[[:space:]]* ) languages="$LANGUAGES" ;;
  * ) languages= ;;
esac

theme=
[ "${THEME:-}" ] && theme="--with-theme='$THEME'"

case "${PYTHON:-1}" in
  no ) lib="${lib} --enable-python=no" ;;
  * )
    if pkg-config --exists python3; then
      lib="${lib} --enable-python=system"
    else
      lib="${lib} --enable-python=no"
    fi
  ;;
esac

if pkg-config --exists gstreamer-1.0; then
  use "${GSTREAMER1:-1}" 1 --disable-gstreamer-1-0
else
  lib="${lib} --disable-gstreamer-1-0"
fi

# build the office development kit (ODK)
if [ "${ODK:-0}" != 0 ]; then
  # generate the doxygen ODK C/C++ documentation
  DOXY="$(exists doxygen || :)"
  if [ "${DOXYGEN:-0}" != 0 ] && [ "${DOXY}" ]; then
    lib="${lib} --with-doxygen=$DOXY"
  else
    lib="${lib} --without-doxygen"
  fi
else
  lib="${lib} --disable-odk"
fi

if [ "${DEBUG:=0}" != 0 ]; then
  SLKCFLAGS="$(printf %s "$SLKCFLAGS" | sed 's/-O2//')"
  case "$DEBUG" in
    dbg ) lib="${lib} --enable-dbgutil" ;;
    symbols ) lib="${lib} --enable-symbols" ;;
    * ) lib="${lib} --enable-debug" ;;
  esac
fi

case "${PCH:-0}" in
  yes|no|system|base|normal|full ) lib="${lib} --enable-pch=$PCH" ;;
esac

if [ "${JAVA_HOME:-}" ] && [ "${JAVA:-1}" = 1 ]; then
  lib="${lib} --with-jdk-home=\"\$JAVA_HOME\""
else
  lib="${lib} --without-java"
fi

# enable experimental features
use "${CHART:-0}"    0 --enable-chart-tests
use "${ICECREAM:-0}" 0 --enable-icecream
use "${MERGELIB:-0}" 0 --enable-mergelibs
use "${VLC:-0}"      0 --enable-vlc

# disable experimental features
use "${AVMEDIA:-1}"   1 --disable-avmedia
use "${EXTENSION:-1}" 1 --disable-extensions
use "${DATABASE:-1}"  1 --disable-database-connectivity
use "${LOADING:-1}"   1 --disable-dynamic-loading
use "${OPENSSL:-1}"   1 --disable-openssl
use "${SCRIPT:-1}"    1 --disable-scripting

# enable features
use "${AVAHI:-0}"      0 --enable-avahi
use "${BREAKPAD:-0}"   0 --enable-breakpad
use "${COMPILER:-0}"   0 --enable-compiler-plugins
use "${CT2n:-0}"       0 --enable-ext-ct2n
use "${DICT:-0}"       0 --with-myspell-dicts
use "${EOT:-0}"        0 --enable-eot
use "${EPM:-0}"        0 --with-epm
use "${FORMULA:-0}"    0 --enable-formula-logger
use "${FUZZERS-0}"     0 --enable-fuzzers
use "${GTK3KDE5:-0}"   0 --enable-gtk3-kde5
use "${KDE5:-0}"       0 --enable-kf5
use "${LANGTOOL:-0}"   0 --enable-ext-languagetool
use "${LTO:-0}"        0 --enable-lto
use "${MPL:-0}"        0 --enable-mpl-subset
use "${NLPSOLVER:-0}"  0 --enable-ext-nlpsolver
use "${NUMBERTEXT:-0}" 0 --enable-ext-numbertext
use "${QT:-0}"         0 --enable-qt5
use "${SAL:-0}"        0 --enable-sal-log
use "${VALGRIND:-0}"   0 --with-valgrind
use "${WERROR:-0}"     0 --enable-werror
use "${WIKI:-0}"       0 --enable-ext-wiki-publisher

# disable features
use "${CANVAS:-1}"     1 --disable-cairo-canvas
use "${CCACHE:-1}"     1 --disable-ccache
use "${CUPS:-1}"       1 --disable-cups
use "${CVE:-1}"        1 --disable-cve-tests
use "${COINMP:-1}"     1 --disable-coinmp
use "${DCONF:-1}"      1 --disable-dconf
use "${DBUS:-1}"       1 --disable-dbus
use "${FIREBIRD:-1}"   1 --disable-firebird-sdbc
use "${FONT:-1}"       1 --without-fonts
use "${GIO:-1}"        1 --disable-gio
use "${GTK3:-1}"       1 --disable-gtk3
use "${GUI:-1}"        1 --disable-gui
use "${LARGEFILE:-1}"  1 --disable-largefile
use "${LDAP:-1}"       1 --disable-ldap
use "${LIBNUMBER:-1}"  1 --disable-libnumbertext
use "${LOTUSPRO:-1}"   1 --disable-lotuswordpro
use "${LPSOLVE:-1}"    1 --disable-lpsolve
use "${LXML:-1}"       1 --disable-lxml
use "${NEON:-1}"       1 --disable-neon
use "${OOENV:-1}"      1 --disable-ooenv
use "${PDF:-1}"        1 --disable-pdfimport
use "${PDFIUM:-1}"     1 --disable-pdfium
use "${POPPLER:-1}"    1 --disable-poppler
use "${POSTGRESQL:-1}" 1 --disable-postgresql-sdbc
use "${RANDR:-1}"      1 --disable-randr
use "${REPORT:-1}"     1 --disable-report-builder
use "${RUNTIME:-1}"    1 --disable-runtime-optimizations
use "${SDREMOTE:-1}"   1 --disable-sdremote
use "${SKIA:-1}"       1 --disable-skia

[ "${XORG:-1}" = 1 ] && lib="${lib} --with-x"

if [ "${SYSTEM_LIBS:-1}" = 1 ]; then
  # dependencies included in slackware
  pkg -b bzip2           --with-system-bzip2
  pkg -b mysql           --with-system-mariadb
  pkg -b ldapurl         --with-system-openldap
  pkg -i boost           --with-system-boost
  pkg -p apr-1           --with-system-apr
  pkg -p bluez           --with-system-bluez
  pkg -p cairo           --with-system-cairo
  pkg -p libclucene-core --with-system-clucene
  pkg -p libcurl         --with-system-curl
  pkg -p epoxy           --with-system-epoxy
  pkg -p expat           --with-system-expat
  pkg -p graphite2       --with-system-graphite
  pkg -p harfbuzz        --with-system-harfbuzz
  pkg -p hunspell        --with-system-hunspell
  pkg -p icu-i18n        --with-system-icu
  pkg -p lcms2           --with-system-lcms2
  pkg -p libodfgen-0.1   --with-system-libodfgen
  pkg -p libpng16        --with-system-libpng
  pkg -p librevenge-0.0  --with-system-librevenge
  pkg -p libvisio-0.1    --with-system-libvisio
  pkg -p libwpd-0.10     --with-system-libwpd
  pkg -p libwpg-0.3      --with-system-libwpg
  pkg -p libxml-2.0      --with-system-libxml
  pkg -p mozilla-nss     --with-system-nss
  pkg -p neon            --with-system-neon
  pkg -p libopenjp2      --with-system-jpeg
  pkg -p openssl         --with-system-openssl
  pkg -p poppler         --with-system-poppler
  pkg -p redland         --with-system-redland
  pkg -p sane-backends   --with-system-sane
  pkg -p zlib            --with-system-zlib

  if [ "${SBO_LIBS:-1}" = 1 ]; then
    # dependencies found at SBo
    pkg -b lp_solve          --with-system-lpsolve
    pkg -i glm               --with-system-glm
    pkg -l libtommath.so.1   --with-system-libtommath
    pkg -p coinmp            --with-system-coinmp
    pkg -p cppunit           --with-system-cppunit
    pkg -p libabw-0.1        --with-system-libabw
    pkg -p atomic_ops        --with-system-libatomic_ops
    pkg -p libcdr-0.1        --with-system-libcdr
    pkg -p libcmis-0.5       --with-system-libcmis
    pkg -p libe-book-0.1     --with-system-libebook
    pkg -p libeot            --with-system-libeot
    pkg -p libepubgen-0.1    --with-system-libepubgen
    pkg -p libetonyek-0.1    --with-system-libetonyek
    pkg -p libexttextcat     --with-system-libexttextcat
    pkg -p libfreehand-0.1   --with-system-libfreehand
    pkg -p liblangtag        --with-system-liblangtag
    pkg -p libnumbertext     --with-system-libnumbertext
    pkg -p libmspub-0.1      --with-system-libmspub
    pkg -p libmwaw-0.3       --with-system-libmwaw
    pkg -p libpagemaker-0.0  --with-system-libpagemaker
    pkg -p libqxp-0.0        --with-system-libqxp
    pkg -p libwps-0.4        --with-system-libwps
    pkg -p libzmf-0.0        --with-system-libzmf
    pkg -p mdds-1.5          --with-system-mdds
    pkg -p mythes            --with-system-mythes
    pkg -p liborcus-0.16     --with-system-orcus
    pkg -p libpq             --with-system-postgresql
    pkg -i qrcodegen         --with-system-qrcodegen
    pkg -p serf-1            --with-system-serf
    pkg -p libstaroffice-0.0 --with-system-libstaroffice
    pkg -p libucpp           --with-system-ucpp
    pkg -p xmlsec1-nss       --with-system-xmlsec
  fi
fi

# check if $BUNDLE is used
case "$lib" in
  *--with-system-mariadb* )
    use "${BUNDLE:-0}" 0 --enable-bundle-mariadb
  ;;
esac

# check if $CRASHDUMP is used
case "$lib" in
  *--enable-breakpad* )
    use "${CRASHDUMP:-1}"  1 --disable-crashdump
  ;;
esac

case "$lib" in
  *--disable-gtk3* )
    :
  ;;
  * )
    if pkg-config --exists gtk+-3.0; then
      use "${INTROSPECTION:-0}" 0 --enable-introspection
    fi
  ;;
esac

# check if $SDRBLUETOOTH is used
case "$lib" in
  *--disable-dbus*|*--disable-sdremote* )
    lib="${lib} --disable-sdremote-bluetooth"
  ;;
  * )
    use "${SDRBLUETOOTH:-1}" 1 --disable-sdremote-bluetooth
  ;;
esac

# check if $TLS or $SSL is used
case "$lib" in *--disable-openssl* ) : ;; * )
  use "${SSL:-0}" 0 --enable-cipher-openssl-backend
  case "${TLS:-0}" in
    openssl|nss ) lib="${lib} --with-tls=$TLS" ;;
  esac
esac

# check which library to use for webdav
webdav=
if [ "${NEON:-1}" = 1 ]; then
  case "${WEB:-0}" in
    neon|serf ) webdav='--with-webdav=$WEB' ;;
    no ) webdav='--without-webdav' ;;
  esac
fi

# disable features if built with $MPL
if [ "${MPL:-0}" != 0 ]; then
  lib="${lib} --disable-report-builder \
              --disable-postgresql-sdbc \
              --disable-lotuswordpro \
              --disable-lpsolve"
  theme='--with-theme=colibre'
  [ "$webdav" = '--without-webdav' ] || webdav='--with-webdav=serf'
  case "$lib" in
    *--with-system-poppler* ) : ;;
    * )  lib="${lib} --disable-pdfimport" ;;
  esac
fi

# prevent downloading of tarballs (adapted from lfs)
SRC_DIR="$(pwd)/$PRGNAM-src-$VERSION"
if [ -d "$SRC_DIR" ]; then
  ln -sf "$SRC_DIR" external/tarballs
else
  mkdir -p external/tarballs
fi

for SRC in dictionaries help translations; do
  if [ -f $CWD/$PRGNAM-$SRC-$VERSION.tar.xz ]; then
    ln -sf $CWD/$PRGNAM-$SRC-$VERSION.tar.xz external/tarballs/
  fi
done

# these environment variables can break building libreoffice
unset DISPLAY

# Don't create the __pycache__ directory.
export PYTHONDONTWRITEBYTECODE=1

# Allow building as root.
sed -i 's/check-if-root //' Makefile.in

# Upgrade liborcus to 0.16.0.
# https://gerrit.libreoffice.org/c/core/+/102502
patch -p1 < $CWD/0001-Upgrade-liborcus-to-0.16.0.patch

# Fix build
sed -i '/libtool.patch.0/d' external/liborcus/UnpackedTarball_liborcus.mk

# Set the configure variables to a portable array
eval "set -- $lib"

CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
./autogen.sh \
  --prefix=$LO_PREFIX \
  --bindir=/usr/bin \
  --libdir=$LO_PREFIX/lib${LIBDIRSUFFIX} \
  --sysconfdir=/etc \
  --mandir=/usr/man \
  --docdir=/usr/doc/$PRGNAM-$VERSION \
  --with-vendor=SlackBuilds \
  --with-lang="$(printf %s "$languages" | tr _ -)" \
  --enable-release-build \
  --without-krb5 \
  --without-gssapi \
  --without-system-dicts \
  --without-junit \
  --with-parallelism="${NUMJOBS:-1}" \
  --build=$ARCH-slackware-linux \
  $theme \
  $webdav \
  "$@"

make build-nocheck
make DESTDIR=$PKG distro-pack-install

mkdir -p $PKG$LO_PREFIX/share/appdata
cp sysui/desktop/appstream-appdata/*.xml $PKG$LO_PREFIX/share/appdata

# don't need these (from alienbob)
rm -f $PKG/gid_Module*
for i in gnome locolor; do
  rm -rf $PKG$LO_PREFIX/share/icons/$i
done

# Replace redundant fonts with symlinks to save space (from alienbob)
case "$lib" in
  *--without-fonts* )
    :
  ;;
  * )
    (
      cd $PKG$LO_PREFIX/lib${LIBDIRSUFFIX}/$PRGNAM/share/fonts/truetype
      for FONTS in DejaVu*.ttf Liberation*.ttf; do
        rm -f "$FONTS"
        ln -sf "/usr/share/fonts/TTF/$FONTS"
      done
    )
  ;;
esac

# Create aliases for locales that have matching languages in LibreOffice
# This enables people with these locales to use the autocorrect function
# Rewritten from Fedora's libreoffice.spec and alienBOB's SlackBuild
( cd $PKG$LO_PREFIX/lib${LIBDIRSUFFIX}/$PRGNAM/share/autocorr

if [ "$languages" = '--with-lang=en-US' ] || [ -z "$languages" ]; then
  # en-ZA exists and has a good autocorrect file with two or three extras
  # that make sense for neighbouring english speaking territories
  rm -f acor_[a-df-z]*.dat acor_e[su]*.dat
  code='en-GB en-US en-ZA'
else
  [ -f acor_lt_LT.dat ] && mv acor_lt_LT.dat acor_lt-LT.dat
  code='en-GB en-US en-ZA af-ZA de-DE es-ES fr-FR it-IT nl-BE sw-SE'
fi

eval "set -- $code"
for lang do
  case "$lang" in
    en-GB) alias='AG AU BS BW BZ CA DK GH HK IE IN JM NG NZ SG TT' ;;
    en-US) alias=PH ;;
    en-ZA) alias='NA ZW' ;;
    af-ZA) alias=NA ;;
    de-DE) alias='AT BE CH LI LU' ;;
    es-ES) alias='AR BO CL CO CR CU DO EC GT HN MX NI PA PE PR PY SV US UY VE' ;;
    fr-FR) alias='BE CA CH LU MC' ;;
    it-IT) alias=CH ;;
    nl-BE) alias=AW ;;
    sv-SE) alias=FI ;;
    *) alias= ;;
  esac
  eval "set -- $alias"
  for link do
    ln -sf "acor_$lang.dat" "acor_${lang%-*}-$link.dat"
  done
done )

if [ $DEBUG = 0 ]; then
  find $PKG -print0 | xargs -0 file | grep -e "executable" -e "shared object" |
    grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null || true
fi

# if installed in /opt or some other location (from lfs)
if [ "$LO_PREFIX" != /usr ]; then
  # Icons
  mkdir -p $PKG/usr/share/pixmaps
  (
    cd $PKG/usr/share/pixmaps
    for i in ../../..$LO_PREFIX/share/icons/hicolor/32x32/apps/*; do
      ln -sf "$i"
    done
  )
  # Desktop menu entries
  mkdir -p $PKG/usr/share/applications
  (
    cd $PKG/usr/share/applications
    for i in ../../..$LO_PREFIX/lib${LIBDIRSUFFIX}/$PRGNAM/share/xdg/*; do
      ln -sf "$i" "$PRGNAM-$(basename "$i")"
    done
  )
fi

mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
cp -a COPYING* ChangeLog README.* $PKG/usr/doc/$PRGNAM-$VERSION
cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cat $CWD/doinst.sh > $PKG/install/doinst.sh

cd $PKG
/sbin/makepkg -l y -c n $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.${PKGTYPE:-tgz}
